package au.com.bus4u.service.impl;

import au.com.bus4u.dao.DaoSupport;
import au.com.bus4u.exception.ServiceException;
import au.com.bus4u.service.PermissionService;
import au.com.bus4u.utils.PageData;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private DaoSupport daoSupport;
    private String mapper = "MenuMapper.";


    @Override
    public int save(PageData pd) throws Exception {

        checkNoNullData(pd);

        pd.remove("menu_id");
        pd.put("menu_type",2);
        pd.put("spread",0);
        return (int) daoSupport.save(mapper+"save", pd);
    }

    private void checkNoNullData(PageData pd) throws Exception  {
        if( pd.get("menu_pid") ==null ||"".equals(pd.get("menu_pid").toString())){
            throw new ServiceException("添加权限失败:菜单ID不能空");
        }
        if( pd.get("menu_name") ==null ||"".equals(pd.get("menu_name").toString())){
            throw new ServiceException("添加权限失败:权限名称不能空");
        }
        if( pd.get("menu_remark") ==null ||"".equals(pd.get("menu_remark").toString())){
            throw new ServiceException("添加权限失败:权限编码不能空");
        }

        if( pd.get("menu_status") ==null ||"".equals(pd.get("menu_status").toString())){
            throw new ServiceException("添加权限失败:menu_status不能空");
        }
        if( pd.get("menu_sort") ==null ||"".equals(pd.get("menu_sort").toString())){
            throw new ServiceException("添加权限失败:menu_sort不能空");
        }

    }


    @Override
    public int delete(Integer menu_id) throws Exception {
        PageData pd = new PageData();
        pd.put("menu_id",menu_id);
        return (int) daoSupport.delete(mapper+"deleteById", pd);
    }

    @Override
    public int edit(PageData pd) throws Exception {
        pd.put("menu_type",2);
        return (int) daoSupport.update(mapper+"edit", pd);
    }

    @Override
    public List<PageData> list(PageData pd) throws Exception {

        pd.put("menu_type",2);

        if(pd.get("menu_name") ==null|| "".equals(pd.get("menu_name").toString()) ){
            pd.remove("menu_name");
        }
        if(pd.get("menu_remark") ==null|| "".equals(pd.get("menu_remark").toString()) ){
            pd.remove("menu_remark");
        }




        return (List<PageData>) daoSupport.findForList(mapper+"list",pd);
    }
    @Override
    public List<PageData> loadAllPermission(PageData pd) throws Exception {
        pd.put("menu_type",2);
        if(pd.get("menu_name") ==null || "".equals(pd.get("menu_name").toString()) ){
            pd.remove("menu_name");
        }
        if(pd.get("menu_remark") ==null || "".equals(pd.get("menu_remark").toString()) ){
            pd.remove("menu_remark");
        }
        if(pd.get("menu_id") ==null || "".equals(pd.get("menu_id").toString())|| "0".equals(pd.get("menu_id").toString()) ){
            pd.remove("menu_id");
        }
        return (List<PageData>) daoSupport.findForList(mapper+"loadAllMenu",pd);
    }

    @Override
    public Integer queryMaxSortNum() throws Exception {
        return (Integer)daoSupport.findForObject(mapper+"queryPermissionMaxSortNum");
    }


    @Override
    public List<PageData> loadAllMenuAndPermission() throws Exception {
        return (List<PageData>) daoSupport.findForList(mapper+"loadAllMenuAndPermission");
    }

    @Override
    public List<Integer> queryRolePermissionIdsByRid(Integer role_id) throws Exception {

        return (List<Integer>) daoSupport.findForList("RolePermissionMapper.queryRolePermissionIdsByRid",role_id);
    }



    @Override
    public List<PageData> loadAllPermissionByMenuIDS(List<Integer> menu_ids) throws Exception {

        return (List<PageData>) daoSupport.findForList(mapper+"loadAllPermissionByMenuIDS",menu_ids);
    }

    @Transactional
    @Override
    public void saveRolePermission(Integer role_id, Integer[] menu_ids) throws Exception {
//        System.out.println("role_id="+role_id);
        PageData pd = new PageData();
        pd.put("role_id",role_id);

        daoSupport.delete("RolePermissionMapper.deleteRolePermissionByRid", role_id);

        if(menu_ids!=null && menu_ids.length>0) {
            for (Integer menu_id : menu_ids) {
                pd.put("menu_id",menu_id);
                daoSupport.save("RolePermissionMapper.saveRolePermission", pd);
            }
        }
    }


    @Override
    public PageData findById(Integer menu_id) throws Exception {
        PageData pd = new PageData();
        pd.put("menu_id",menu_id);

        daoSupport.findForObject(mapper+"deleteRoleMenuByMenuId",pd);//删除关联表role_menu中的数据

        return (PageData) daoSupport.findForObject(mapper+"list",pd);
    }



    @Override
    public int deleteAll(String[] DATA_IDS) throws Exception {

        return (int)daoSupport.batchDelete(mapper+"deleteAll", DATA_IDS);
    }

    @Override
    public List<PageData> findByPId(Integer menu_pid) throws Exception {
        PageData pd = new PageData();
        pd.put("menu_pid",menu_pid);
        return (List<PageData>) daoSupport.findForList(mapper+"list",pd);
    }

    @Override
    public List<PageData> findByRoleIdAndMenuPId(Integer role_id, Integer menu_pid) throws Exception {
        List<PageData> list= new ArrayList<>();
        //通过父级菜单id查询子菜单list
        List<PageData> roleMenu = findByPId(menu_pid);
//        System.err.println("roleMenu = " + roleMenu);
        //遍历子菜单list获取子菜单id
        PageData pd = new PageData();
        pd.put("role_id",role_id);
        for (PageData menu:roleMenu){
            pd.put("menu_id",menu.getInt("menu_id"));
            PageData forObject = (PageData) daoSupport.findForObject(mapper + "findByRoleIdAndMenuId", pd);
            if(forObject != null){
                pd.remove("menu_id");
                List<PageData> children = new ArrayList<>();
                if( forObject != null){
                    children = findByRoleIdAndMenuPId(role_id, forObject.getInt("menu_id"));
                }
                forObject.put("children",children);
                list.add(forObject);
            }
        }
        return list;
    }

    /**
     * 获取菜单tree数据
     * @return
     * @throws Exception
     */
    @Override
    public List<PageData> loadPermissionTree(Integer menu_pid) throws Exception {
        PageData pd = new PageData();
        pd.put("menu_pid",menu_pid);
//        pd.put("menu_type",1);
        //通过父级菜单id查询子菜单list
        List<PageData> roleMenu = (List<PageData>) daoSupport.findForList(mapper + "findMenuTreeListByMenuPId", pd);
        for (PageData menu:roleMenu){
            List<PageData> children = new ArrayList<>();
            children = loadPermissionTree(menu.getInt("id"));
            menu.put("children",children);
            menu.put("spread",menu.getInt("spread") == 0 ? false : true);
        }
        return roleMenu;
    }




    private PageData getCurrentUser(){
        return (PageData) SecurityUtils.getSubject().getSession().getAttribute("currentUser");
    }
    private String getCurrentUserID(){
        PageData pd = getCurrentUser();
        String user_id = pd.get("user_id").toString();
        return user_id;

    }
    private Integer getCurrentUserRoleID(){
        PageData pd = getCurrentUser();
        Integer role_id = pd.getInt("role_id");
        return role_id;

    }


}
